package cate.game.client;

import cate.game.GameBody;
import cate.game.client.msg.MsgOutput;
import cate.game.client.netty.NettyContext;
import cate.game.role.Role;
import cp.solution.business.sys.account.dto.AccountLoginData;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;

public class ClientContext {

    /** cid : Client ChannelHandlerContext Id */
    @Getter@Setter
    private String cid;

    @Getter@Setter
    private NettyContext netty;

    @Getter@Setter
    private long activeTime;

    /** 关联的Role */
    @Getter
    private Role role;

    public void bindRole(Role role, GameBody game) {
        this.role = role;
        this.role.setCc(this);
        game.role.putActive(role);
    }

    @Getter@Setter
    private AccountLoginData loginData;

    public void send(MsgOutput msg) {
        if(netty != null){
            netty.send(msg);
        }
    }

    public void sendNow(MsgOutput msg) {
        if(netty != null){
            netty.sendNow(msg);
        }
    }

    public void flush(){
        if (netty != null) {
            netty.flush();
        }
    }

    public void active(){
        this.setActiveTime(System.currentTimeMillis());
    }

    /** 是否有效 */
    public boolean valid() {
        return System.currentTimeMillis() - activeTime < 180000;
    }

    public void kickOff(GameBody game){
        if(StringUtils.isNotBlank(cid)){
            if(game.client.contextHolder.contains(this.cid)){
                game.client.contextHolder.unregister(this.cid);
            }
        }
        if (netty != null) {
            netty.close();
        }
    }

    /** 创建一个下线的虚拟cc */
    public static ClientContext createOffline() {
        ClientContext cc = new ClientContext();
        cc.active();
        return cc;
    }
}
